import QtQuick 1.0
import "G.js" as G

ListView { id: idSpotsList
    cacheBuffer: 100
    model: idSpotsModel
    delegate: idSpotsDelegate

    ListHeader {
        id: idListHeader
        onSearch:  {
            idSpotsList.refresh();
            if (searchText != "Search" && searchText != "") {
                idSpotsList.state = "SearchingSpots"
            } else {
                idSpotsList.state = "LoadingSpots"
            }
        }
    }

    header: Image {
        width: parent.width
        height: 70;
        source: "art/macapp_cellbg.png"
    }

    signal spotsSuccess
    signal spotsError
    signal refresh
    signal recommended(int spotId, bool spotInCollection)
    signal imageSelected(string url)

    states: [
        State {
            name: "LoadingSpots"
            StateChangeScript {
                script: {
                    spotsWorker.sendMessage({'model': idSpotsModel, 'g': G.g});
                }
            }
        },
        State {
            name: "SearchingSpots"
            StateChangeScript {
                script: {
                    spotsWorker.sendMessage({'model': idSpotsModel, 'g': G.g, 'search': idListHeader.searchText });
                }
            }
        },
        State {
            name: "LoadedSpots"
        },
        State {
            name: "LoadingImages"
            StateChangeScript {
                script: {
                    imageWorker.sendMessage(idSpotsList.message)
                }
            }
        }
    ]

    ScrollBar {
        id: idSpotsListScrollBar
        scrollArea: idSpotsList;
        height: idSpotsList.height;
        width: 8;
        anchors.top: idSpotsList.top;
        anchors.right: idSpotsList.right
        z: idSpotsListScrollBar.opacity == 1 ? 2 : 0
    }

    WorkerScript {
        id: spotsWorker
        source: "SpotsLoader.js"
        onMessage: {
            if (messageObject.result == 'SUCCESS') {
                idSpotsList.state = "LoadedSpots"
                idSpotsList.spotsSuccess();
            } else {
                idSpotsList.spotsError();
            }
        }
    }

    WorkerScript {
        id: imageWorker
        source: "ImageLoader.js"
        onMessage: {
            if (messageObject.result == 'SUCCESS') {
                idSpotsList.state = "LoadedSpots"
//                idSpotsList.spotsSuccess();
            } else {
//                idSpotsList.spotsError();
            }
        }
    }

    property variant message

    Component {
        id: idSpotsDelegate
        SpotsDelegate {
            onLoadImages: {
                idSpotsList.message = message
                idSpotsList.state = "LoadingImages"
            }
            onImageSelected: idSpotsList.imageSelected(url)
        }
    }

    ListModel {
        id: idSpotsModel
    }

}

